import React, { memo, useCallback, useMemo } from 'react';
import { Card, Button, Space, Badge, Tooltip } from 'antd';
import { LeftOutlined, RightOutlined, PlusOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';

dayjs.extend(isBetween);
import type { IWeeklyCalendarViewProps, ITimeSlot } from '@/types/components/schedule';
import ScheduleInstanceCard from '../ScheduleInstanceCard';
import styles from './WeeklyCalendarView.module.css';

/**
 * 周历视图组件
 * @description 显示一周的课程安排，以网格形式展示
 */
const WeeklyCalendarView: React.FC<IWeeklyCalendarViewProps> = memo(({
  weekStartDate,
  scheduleInstances,
  students,
  courses,
  selectedStudents,
  onDateClick,
  onInstanceClick,
  onWeekChange,
  onAddSchedule,
  className,
  readonly = false
}) => {
  // 生成一周的日期
  const weekDates = useMemo(() => {
    const startDate = dayjs(weekStartDate);
    return Array.from({ length: 7 }, (_, i) => startDate.add(i, 'day'));
  }, [weekStartDate]);

  // 获取本周的课程实例
  const weekInstances = useMemo(() => {
    const startDate = dayjs(weekStartDate);
    const endDate = startDate.add(6, 'day');
    
    return scheduleInstances
      .filter(instance => {
        const instanceDate = dayjs(instance.date);
        return instanceDate.isBetween(startDate, endDate, 'day', '[]');
      })
      .filter(instance => 
        selectedStudents.length === 0 || selectedStudents.includes(instance.studentId)
      );
  }, [scheduleInstances, weekStartDate, selectedStudents]);

  // 生成时间段
  const timeSlots = useMemo((): ITimeSlot[] => {
    const slots: ITimeSlot[] = [];
    const times = new Set<string>();
    
    // 收集所有时间点
    weekInstances.forEach(instance => {
      times.add(instance.startTime);
      times.add(instance.endTime);
    });
    
    const sortedTimes = Array.from(times).sort();
    
    // 生成时间段
    for (let i = 0; i < sortedTimes.length - 1; i++) {
      slots.push({
        startTime: sortedTimes[i],
        endTime: sortedTimes[i + 1],
        label: `${sortedTimes[i]}-${sortedTimes[i + 1]}`
      });
    }
    
    return slots;
  }, [weekInstances]);

  // 获取学生信息
  const getStudent = useCallback((studentId: string) => {
    return students.find(s => s.id === studentId);
  }, [students]);

  // 获取课程信息
  const getCourse = useCallback((courseId: string) => {
    return courses.find(c => c.id === courseId);
  }, [courses]);

  // 获取指定日期和时间段的课程实例
  const getInstancesForSlot = useCallback((date: dayjs.Dayjs, timeSlot: ITimeSlot) => {
    const dateStr = date.format('YYYY-MM-DD');
    return weekInstances.filter(instance => 
      instance.date === dateStr &&
      instance.startTime === timeSlot.startTime &&
      instance.endTime === timeSlot.endTime
    );
  }, [weekInstances]);

  // 处理上一周
  const handlePrevWeek = useCallback(() => {
    const prevWeek = dayjs(weekStartDate).subtract(1, 'week').format('YYYY-MM-DD');
    onWeekChange?.(prevWeek);
  }, [weekStartDate, onWeekChange]);

  // 处理下一周
  const handleNextWeek = useCallback(() => {
    const nextWeek = dayjs(weekStartDate).add(1, 'week').format('YYYY-MM-DD');
    onWeekChange?.(nextWeek);
  }, [weekStartDate, onWeekChange]);

  // 处理日期点击
  const handleDateClick = useCallback((date: dayjs.Dayjs) => {
    onDateClick?.(date.format('YYYY-MM-DD'));
  }, [onDateClick]);

  // 处理添加课程
  const handleAddSchedule = useCallback((date: dayjs.Dayjs, timeSlot?: ITimeSlot) => {
    onAddSchedule?.(date.format('YYYY-MM-DD'), timeSlot?.label);
  }, [onAddSchedule]);

  // 渲染网格单元格
  const renderGridCell = (date: dayjs.Dayjs, timeSlot: ITimeSlot) => {
    const instances = getInstancesForSlot(date, timeSlot);
    const isToday = date.isSame(dayjs(), 'day');
    
    return (
      <div
        key={`${date.format('YYYY-MM-DD')}-${timeSlot.label}`}
        className={`${styles.gridCell} ${isToday ? styles.today : ''}`}
        onClick={() => handleDateClick(date)}
      >
        {instances.length > 0 ? (
          <div className={styles.instancesContainer}>
            {instances.map(instance => {
              const student = getStudent(instance.studentId);
              const course = getCourse(instance.courseId);
              
              if (!student || !course) return null;
              
              return (
                <div
                  key={instance.id}
                  className={styles.instanceItem}
                  onClick={(e) => {
                    e.stopPropagation();
                    onInstanceClick?.(instance);
                  }}
                >
                  <div 
                    className={styles.instanceIndicator}
                    style={{ backgroundColor: course.color }}
                  />
                  <div className={styles.instanceInfo}>
                    <div className={styles.courseName}>{course.name}</div>
                    <div className={styles.studentName}>{student.name}</div>
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          !readonly && (
            <div 
              className={styles.emptyCell}
              onClick={(e) => {
                e.stopPropagation();
                handleAddSchedule(date, timeSlot);
              }}
            >
              <PlusOutlined className={styles.addIcon} />
            </div>
          )
        )}
      </div>
    );
  };

  return (
    <div className={`${styles.weeklyCalendarView} ${className || ''}`}>
      {/* 头部控制区域 */}
      <Card className={styles.headerCard} size="small">
        <div className={styles.headerContent}>
          <div className={styles.weekControls}>
            <Button
              type="text"
              icon={<LeftOutlined />}
              onClick={handlePrevWeek}
              className={styles.navButton}
            />
            <span className={styles.weekRange}>
              {dayjs(weekStartDate).format('YYYY年MM月DD日')} - {dayjs(weekStartDate).add(6, 'day').format('MM月DD日')}
            </span>
            <Button
              type="text"
              icon={<RightOutlined />}
              onClick={handleNextWeek}
              className={styles.navButton}
            />
          </div>
          
          <div className={styles.weekInfo}>
            <Badge 
              count={weekInstances.length} 
              showZero 
              className={styles.countBadge}
            />
          </div>
        </div>
      </Card>

      {/* 日历网格 */}
      <Card className={styles.calendarCard}>
        <div className={styles.calendarGrid}>
          {/* 头部：星期标题 */}
          <div className={styles.headerRow}>
            <div className={styles.timeHeader}>时间</div>
            {weekDates.map(date => (
              <div 
                key={date.format('YYYY-MM-DD')}
                className={`${styles.dateHeader} ${date.isSame(dayjs(), 'day') ? styles.today : ''}`}
              >
                <div className={styles.weekdayName}>{date.format('ddd')}</div>
                <div className={styles.dateNumber}>{date.format('DD')}</div>
              </div>
            ))}
          </div>

          {/* 时间段行 */}
          {timeSlots.map(timeSlot => (
            <div key={timeSlot.label} className={styles.timeRow}>
              <div className={styles.timeLabel}>
                <div className={styles.timeSlotText}>{timeSlot.label}</div>
              </div>
              {weekDates.map(date => renderGridCell(date, timeSlot))}
            </div>
          ))}

          {/* 空状态 */}
          {timeSlots.length === 0 && (
            <div className={styles.emptyState}>
              <div className={styles.emptyMessage}>本周暂无课程安排</div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
});

WeeklyCalendarView.displayName = 'WeeklyCalendarView';

export default WeeklyCalendarView;